<template>
  <div>
    <warning-bar title="注：右上角头像下拉可切换角色" />
    <main-layout>
      <template v-slot:top>
        <el-form ref="searchForm" :inline="true" :model="searchInfo">
          <el-form-item label="姓名">
            <el-input v-model="searchInfo.name" placeholder="姓名" clearable/>
          </el-form-item>
          <el-form-item label="用户名">
            <el-input v-model="searchInfo.userName" placeholder="用户名" clearable/>
          </el-form-item>
          <el-form-item label="手机号">
            <el-input v-model="searchInfo.phone" placeholder="手机号" clearable/>
          </el-form-item>
        <el-form-item label="角色">
          <el-select v-model="searchInfo.roleId" clearable placeholder="请选择" style="width: 140px;">
            <el-option
              v-for="item in roleOptions"
              :key="item.value"
              :label="`${item.label}`"
              :value="item.value"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="类型">
          <el-select v-model="searchInfo.type" clearable placeholder="请选择" style="width: 140px;">
            <!-- <el-option :value="1" label="普通用户" />
            <el-option :value="2" label="经销商" />
            <el-option :value="3" label="系统管理员" /> -->
          <el-option
            v-for="item in typeOptions"
            :key="item.value"
            :label="`${item.label}`"
            :value="item.value"
          />
          </el-select>
        </el-form-item>
          <el-form-item label="状态">
            <el-select v-model="searchInfo.state" clearable placeholder="请选择" style="width: 140px;">
          <el-option
            v-for="item in stateOptions"
            :key="item.value"
            :label="`${item.label}`"
            :value="item.value"
          />
            </el-select>
          </el-form-item>
        <el-form-item label="来源">
          <el-select v-model="searchInfo.source" clearable placeholder="请选择" style="width: 140px;">
            <!-- <el-option :value="1" label="后台添加" />
            <el-option :value="2" label="APP注册" />
            <el-option :value="3" label="微信小程序注册" /> -->
          <el-option
            v-for="item in sourceOptions"
            :key="item.value"
            :label="`${item.label}`"
            :value="item.value"
          />
          </el-select>
        </el-form-item>
          <el-form-item>
            <el-button size="small" type="primary" icon="search" @click="onSubmit">查询</el-button>
            <el-button size="small" icon="refresh" @click="onReset">重置</el-button>
          </el-form-item>
        </el-form>
      </template>

      <div class="gva-btn-list">
        <el-button size="small" type="primary" icon="plus" @click="addUser">新增用户</el-button>
      </div>

      <c-table :page="{pageSize,pageIndex,total}" :lists="tableData" @current-change="handleCurrentChange" @size-change="handleSizeChange">
        <el-table-column align="left" label="头像" min-width="75">
          <template #default="scope">
          <CustomPic style="margin-top:8px" :pic-src="scope.row.headerImg" />
          </template>
        </el-table-column>
        <el-table-column align="left" label="类型" min-width="100" prop="type" >
          <template #default="scope">
            <div v-for="item in typeOptions"><span v-if="item.value === scope.row.type">{{item.label}}</span></div>
          </template>
        </el-table-column>
        <el-table-column align="left" label="姓名" min-width="120" prop="name" />
        <el-table-column align="left" label="用户名" min-width="120" prop="userName" />
        <el-table-column align="left" label="昵称" min-width="120" prop="nickName" />
        <el-table-column align="left" label="手机号" min-width="110" prop="phone" />
        <el-table-column align="left" label="邮箱" min-width="180" prop="email" />
        <el-table-column align="left" label="性别" min-width="60" prop="sex" >
          <template #default="scope">
            <div v-for="item in sexOptions"><span v-if="item.value === scope.row.sex">{{item.label}}</span></div>
          </template>
        </el-table-column>
        <el-table-column align="left" label="状态" min-width="60" prop="state" >
          <template #default="scope">
            <div v-for="item in stateOptions"><span v-if="item.value === scope.row.state">{{item.label}}</span></div>
          </template>
        </el-table-column>
            <el-table-column align="left" label="来源" min-width="140" prop="source" >
          <template #default="scope">
            <div v-for="item in sourceOptions"><span v-if="item.value === scope.row.source">{{item.label}}</span></div>
          </template>
        </el-table-column>
        <el-table-column align="left" label="用户角色" min-width="220" prop="roleIds">
          <template #default="scope">
            <el-cascader
              v-model="scope.row.roleIdList"
              :options="roleOptions"
              :show-all-levels="false"
              collapse-tags
              :props="{ multiple:true,checkStrictly: true,disabled:'disabled',emitPath:false}"
              :clearable="false"
              @visible-change="(flag)=>{changeRole(scope.row,flag)}"
              @remove-tag="()=>{changeRole(scope.row,false)}"
            />
          </template>
        </el-table-column>
        <el-table-column label="操作" min-width="160" fixed="right">
          <template #default="scope">
            <el-button type="text" icon="edit" size="small" @click="openEdit(scope.row)">编辑</el-button>
            <el-button type="text" icon="magic-stick" size="small" @click="resetPasswordFunc(scope.row)">重置密码</el-button>
          </template>
        </el-table-column>
      </c-table>

      
  </main-layout>
    <el-dialog
      v-model="addUserDialog"
      custom-class="user-dialog"
      title="用户"
      :show-close="false"
      :close-on-press-escape="false"
      :close-on-click-modal="false"
    >
      <div style="height:60vh;overflow:auto;padding:0 12px;">
        <el-form ref="userForm" :rules="rules" :model="userInfo" label-width="80px">
          <el-form-item label="类型" prop="type">
			<el-select v-model="userInfo.type" placeholder="请选择" :style="{ width: '100%' }" >
				<el-option
				  v-for="item in typeOptions"
				  :key="item.value"
				  :label="`${item.label}`"
				  :value="item.value"
				/>
			</el-select>
          </el-form-item>
		  <el-form-item label="用户名" prop="userName">
            <el-input :disabled="dialogFlag === 'edit'" v-model="userInfo.userName" />
          </el-form-item>
		  <el-form-item label="姓名" prop="name">
		    <el-input v-model="userInfo.name" />
		  </el-form-item>
          <el-form-item v-if="dialogFlag === 'add'" label="密码" prop="password">
            <el-input v-model="userInfo.password" />
          </el-form-item>
          <el-form-item label="昵称" prop="nickName">
            <el-input v-model="userInfo.nickName" />
          </el-form-item>
          <el-form-item label="手机号" prop="phone">
            <el-input v-model="userInfo.phone" />
          </el-form-item>
          <el-form-item label="邮箱" prop="email">
            <el-input v-model="userInfo.email" />
          </el-form-item>
		  <el-form-item label="性别" prop="sex">
			<el-select v-model="userInfo.sex" placeholder="请选择" :style="{ width: '100%' }" >
				<el-option
				  v-for="item in sexOptions"
				  :key="item.value"
				  :label="`${item.label}`"
				  :value="item.value"
				/>
			</el-select>
		  </el-form-item>
		  <el-form-item label="生日" prop="birthday">
		    <!-- <el-input v-model="userInfo.birthday" /> -->
			<el-date-picker v-model="userInfo.birthday" type="date" format="YYYY-MM-DD" value-format="YYYY-MM-DD" placeholder="请选择生日" />
		  </el-form-item>
		  <el-form-item label="住址" prop="address">
		    <el-input v-model="userInfo.address" />
		  </el-form-item>
		  <el-form-item label="状态" prop="state">
			<el-select v-model="userInfo.state" placeholder="请选择" :style="{ width: '100%' }" >
				<el-option
				  v-for="item in stateOptions"
				  :key="item.value"
				  :label="`${item.label}`"
				  :value="item.value"
				/>
			</el-select>
		  </el-form-item>
		  <el-form-item label="来源" prop="source">
			<el-select disabled v-model="userInfo.source" placeholder="请选择" :style="{ width: '100%' }" >
				<el-option
				  v-for="item in sourceOptions"
				  :key="item.value"
				  :label="`${item.label}`"
				  :value="item.value"
				/>
			</el-select>
		  </el-form-item>
          <el-form-item label="用户角色" prop="roleIds">
            <el-cascader
              v-model="userInfo.roleIdList"
              style="width:100%"
              :options="roleOptions"
              :show-all-levels="false"
              :props="{ multiple:true,checkStrictly: true,disabled:'disabled',emitPath:false}"
              :clearable="false"
            />
          </el-form-item>
          <el-form-item label="头像" label-width="80px">
            <div style="display:inline-block" @click="openHeaderChange">
              <img v-if="userInfo.headerImg" class="header-img-box" :src="(userInfo.headerImg && userInfo.headerImg.slice(0, 4) !== 'http')?path+userInfo.headerImg:userInfo.headerImg">
              <div v-else class="header-img-box">从媒体库选择</div>
            </div>
          </el-form-item>
        </el-form>
      </div>

      <template #footer>
        <div class="dialog-footer">
          <el-button size="small" @click="closeAddUserDialog">取 消</el-button>
          <el-button size="small" type="primary" @click="enterAddUserDialog">确 定</el-button>
        </div>
      </template>
    </el-dialog>
    <ChooseImg ref="chooseImg" :target="userInfo" :target-key="`headerImg`" />
  </div>
</template>

<script>
export default {
  name: 'User',
}
</script>

<script setup>

import {
  getUserList,
  saveUserRoleList,
  deleteUser,
  saveUser, resetUserPassword
} from '@/api/user'

import mainLayout from '@/components/custom/mainLayout.vue'
import cTable from '@/components/custom/cTable.vue'

import { getRoleList } from '@/api/role'
import { getDict } from '@/utils/dictionary'
import CustomPic from '@/components/customPic/index.vue'
import ChooseImg from '@/components/chooseImg/index.vue'
import warningBar from '@/components/warningBar/warningBar.vue'

import { nextTick, ref, watch } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
const path = ref(import.meta.env.VITE_BASE_API)

const pageIndex = ref(1)
const total = ref(0)
const pageSize = ref(20)
const tableData = ref([])
const searchInfo = ref({})
const roleOptions = ref([])
// 性别
const sexOptions = ref([])
// 类型
const typeOptions = ref([])
// 状态
const stateOptions = ref([])
// 来源
const sourceOptions = ref([])

const onReset = () => {
  searchInfo.value = {}
}
// 搜索
const onSubmit = () => {
  getTableData()
}
// 分页
const handleSizeChange = (val) => {
  pageSize.value = val
  getTableData()
}

const handleCurrentChange = (val) => {
  pageIndex.value = val
  getTableData()
}

// 查询
const getTableData = async() => {
  const table = await getUserList({ pageIndex: pageIndex.value, pageSize: pageSize.value, role: true, ...searchInfo.value })
  if (table.code === 0) {
    tableData.value = table.data.list
    total.value = table.data.total
  }
}

watch(tableData, () => {
  setRoleIdList()
})

const initPage = async() => {
  // 查询用户角色列表
  {
	  const res = await getRoleList({ pageIndex: 1, pageSize: 999 })
	  if(res.code === 0){
		  const list = res.data.list
		  list && list.forEach((item) => {
			  roleOptions.value.push({
				  value: item.id,
				  label: item.name
			  })
		  })
	  }
  }
  // 性别
  {
	  var op = await getDict("user_sex")
	  if(op){
	  	sexOptions.value = op
	  }
  }
  // 类型
  {
	  var op = await getDict("user_type")
	  if(op){
	  	typeOptions.value = op
	  }
  }
  // 状态
  {
	  var op = await getDict("initiate_mode")
	  if(op){
		  stateOptions.value = op
	  }
  }
  // 来源
  {
	  var op = await getDict("user_source")
	  if(op){
	  	sourceOptions.value = op
	  }
  }
  getTableData()
}

initPage()

const resetPasswordFunc = (row) => {
  ElMessageBox.confirm(
    '是否将此用户密码重置为123456?',
    '警告',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning',
    }
  ).then(async() => {
    const res = await resetUserPassword({
      id: row.id,
    })
    if (res.code === 0) {
      ElMessage({
        type: 'success',
        message: res.msg,
      })
    } else {
      ElMessage({
        type: 'error',
        message: res.msg,
      })
    }
  })
}
const setRoleIdList = () => {
  tableData.value && tableData.value.forEach((user) => {
    const roleIdList = user.roleIds && user.roleIds.split(",")
	if(roleIdList){
		user.roleIdList = []
		roleIdList.forEach(id => user.roleIdList.push(Number(id)))
	}
  })
}

const chooseImg = ref(null)
const openHeaderChange = () => {
  chooseImg.value.open()
}

const deleteUserFunc = async(row) => {
  const res = await deleteUser({ id: row.id })
  if (res.code === 0) {
    ElMessage.success('删除成功')
    row.visible = false
    await getTableData()
  }
}

// 弹窗相关
const userInfo = ref({
  username: '',
  password: '',
  nickName: '',
  headerImg: '',
  sex: 3,
  birthday: '',
  state: 1,
  source: 1,
  roleIds: '',
  roleIdList: [],
  sideMode: 'dark',
  activeColor: '#4D70FF',
  baseColor: '#fff'
})

const rules = ref({
  type: [
    { required: true, message: '请选择用户类型', trigger: 'blur' },
  ],
  userName: [
    { required: true, message: '请输入用户名', trigger: 'blur' },
    { min: 1, message: '最低1位字符', trigger: 'blur' },
	{ max: 30, message: '最高30位字符', trigger: 'blur' }
  ],
  name: [
    { required: true, message: '请输入用户名', trigger: 'blur' },
    { min: 2, message: '最低2位字符', trigger: 'blur' }
  ],
  password: [
    { required: true, message: '请输入用户密码', trigger: 'blur' },
    { min: 6, message: '最低6位字符', trigger: 'blur' }
  ],
  nickName: [
    { required: true, message: '请输入用户昵称', trigger: 'blur' }
  ],
  phone: [
    { required: true, message: '请输入手机号', trigger: 'blur' }
  ]
})
const userForm = ref(null)
const enterAddUserDialog = async() => {
  userForm.value.validate(async valid => {
    if (valid) {
      const req = {
        ...userInfo.value
      }
	  if(req.birthday && req.birthday.length == 10){
		  req.birthday = req.birthday + "T00:00:00+08:00"
	  }
      if (dialogFlag.value === 'add') {
        const res = await saveUser(req)
        if (res.code === 0) {
          ElMessage({ type: 'success', message: '创建成功' })
          await getTableData()
          closeAddUserDialog()
        }
      }
      if (dialogFlag.value === 'edit') {
        const res = await saveUser(req)
        if (res.code === 0) {
          ElMessage({ type: 'success', message: '编辑成功' })
          await getTableData()
          closeAddUserDialog()
        }
      }
    }
  })
}

const addUserDialog = ref(false)
const closeAddUserDialog = () => {
  userForm.value.resetFields()
  userInfo.value.headerImg = ''
  userInfo.value.roleIdList = []
  addUserDialog.value = false
}

const dialogFlag = ref('add')

const addUser = () => {
	userInfo.value = {
		username: '',
		password: '',
		nickName: '',
		headerImg: '',
		sex: 3,
		birthday: '',
		state: 1,
		source: 1,
		roleIds: '',
		roleIdList: [],
		sideMode: 'dark',
		activeColor: '#4D70FF',
		baseColor: '#fff'
	}
  dialogFlag.value = 'add'
  addUserDialog.value = true
}
const changeRole = async(row, flag) => {
  if (flag) {
    return
  }
  await nextTick()
  const res = await saveUserRoleList({
    id: row.id,
    ids: row.roleIdList
  })
  if (res.code === 0) {
    ElMessage({ type: 'success', message: '角色设置成功' })
  }
}

const openEdit = (row) => {
  dialogFlag.value = 'edit'
  userInfo.value = JSON.parse(JSON.stringify(row))
  addUserDialog.value = true
}

</script>

<style lang="scss">
.user-dialog {
  .header-img-box {
  width: 200px;
  height: 200px;
  border: 1px dashed #ccc;
  border-radius: 20px;
  text-align: center;
  line-height: 200px;
  cursor: pointer;
}
  .avatar-uploader .el-upload:hover {
    border-color: #409eff;
  }
  .avatar-uploader-icon {
    border: 1px dashed #d9d9d9 !important;
    border-radius: 6px;
    font-size: 28px;
    color: #8c939d;
    width: 178px;
    height: 178px;
    line-height: 178px;
    text-align: center;
  }
  .avatar {
    width: 178px;
    height: 178px;
    display: block;
  }
}
.nickName{
  display: flex;
  justify-content: flex-start;
  align-items: center;
}
.pointer{
  cursor: pointer;
  font-size: 16px;
  margin-left: 2px;
}
</style>
